<?php

namespace app\admin\controller;

use app\admin\model\Paper;
use app\base\model\User;
use app\common\controller\AdminBase;
use think\Cache;
use think\Request;
use think\Config;

class Room extends AdminBase {
  protected $model, $modelQuestion, $modelClass, $modelUser, $modelConfig, $modelPaper;

  public function __construct(Request $request = NULL) {
    parent::__construct($request);
    $this->model = new \app\admin\model\Room();
    $this->modelQuestion = new \app\admin\model\Question();
    $this->modelClass = new \app\admin\model\Classes();
    $this->modelUser = new User();
    $this->modelConfig = new \app\admin\model\Config();
    $this->modelPaper = new Paper();
  }

  public function _initialize() {
    parent::_initialize();
  }

  public function index() {
    $map = [];
    if ($this->roleId == 2) {
      $map = [
        'r.teacher_uid' => $this->uid,
      ];
    }
    //
    $rows = $this->model
      ->alias('r')
      ->where($map)
      ->join('__CLASS__ c', 'c.id=r.class_id', 'left')
      ->join('__BASE_USER__ u', 'u.id=r.teacher_uid', 'left')
      ->field('r.*,c.title as class_title,u.realname')
      ->order('r.id DESC')
      ->paginate();

    return view('', [
      'rows'   => $rows,
      'roleId' => $this->roleId]);
  }

  public function add() {
    return self::edit();
  }

  public function edit() {
    $classId = 0;//班级ID
    $id = input('id/d', 0, 'abs');
    $row = ($id > 0) ? $this->model->find($id) : [];
    if ($row && $row['status'] != 0) $this->error('考试已经开始不能修改');
    $modelPaper = new Paper();
    //题库设置
    $config = $this->modelConfig->getNewest();
    if (!$config) $this->error('管理员尚未设定题库，无法新建考试 ');
    if ($this->roleId == 2) {
      $classId = $this->modelClass->getTeacherClassId($this->uid);
    }
    if (!request()->isPost()) {
      $qType = config('question')['type'];
      $qConfig = json_decode($config['q_config'], TRUE);

      $papers = $modelPaper->getRoomPaper($id);

      //dump($papers);

      return view('edit', [
        'row'     => $row,
        'config'  => $config,
        'qConfig' => $qConfig,
        'qType'   => $qType,
        'classId' => $classId,
        'papers'  => json_encode(['users' => $papers]),
      ]);
    }
    $form = input('form/a', NULL);
    if (!$form) $this->error(lang('form empty'));
    $form['class_id'] = $classId;
    $form['q_config'] = $config['q_config'];
    $form['exam_duration'] = $config['exam_duration'];
    $form['pass_score'] = $config['pass_score'];
    $form['paper_count'] = count($form['papers']);
    $form['teacher_uid'] = $this->uid;
    if ($form['paper_count'] > $config['capacity']) {
      $this->error('管理员设置了考场最多只能' . $config['capacity'] . '人考试');
    }
    $paperData = $form['papers'];
    $this->model->startTrans();
    try {
      if ($id > 0) {
        $modelPaper->where('room_id', $id)->delete();
        $this->model->allowField(TRUE)->save($form, ['id' => $id]);
      } else {
        $this->model->allowField(TRUE)->save($form);
        $id = $this->model->getLastInsID();
      }
      foreach ($paperData as &$v) {
        $v['room_id'] = $id;
      }
      $modelPaper->saveAll($paperData);
      $this->model->commit();
    } catch (\Exception $e) {
      $this->model->rollback();
      $this->error($e->getMessage());
    }
    cmf_log('新增/编辑考试', $id, $classId > 0 ? '班级ID' . $classId : '补考');
    $this->success(lang('success'), 'index');
  }

  public function view() {
    $id = input('id/d', 0, 'abs');
    $row = ($id > 0) ? $this->model->find($id) : [];
    if (!$row) $this->error('考场不存在');
    $modelPaper = new Paper();
    //题库设置
    $classes = $this->modelClass->getColumn('title', 'id');
    $teachers = $this->modelUser->getTeachers();
    $qType = config('question')['type'];
    $papers = $modelPaper->getRoomPaper($id);

    //将答案转换为abcd
    $answers = array_map(function ($v) {
      $arr = $v['answers'] ? json_decode($v['answers'], TRUE) : [];
      $arr2 = array_map(function ($v) {
        return chr(65 + $v);
      }, $arr);
      ksort($arr2);

      return $arr2;
    }, $papers);

    return view('', [
      'row'      => $row,
      'qConfig'  => json_decode($row['q_config'], TRUE),
      'answers'  => $answers,
      'classes'  => $classes,
      'teachers' => $teachers,
      'qType'    => $qType,
      'papers'   => $papers,
    ]);

  }

  /**
   * 生成试卷功能
   */
  public function buildPaper() {
    $paperCount = input('count/d', 0, 'abs');
    $config = $this->modelConfig->getNewest();
    if (!$config) $this->error('管理员尚未设定题库，无法新建考试 ');

    $modelPaper = new Paper();

    $qConfig = json_decode($config['q_config'], TRUE);
    $questions = [];
    $qType = config('question')['type'];
    foreach ($qConfig as $type => $v) {
      //获取各个类型中有效的题目数量
      $map = ['type'    => $type,
              'disable' => 0];
      $questions[ $type ] = $this->modelQuestion->where($map)->column('id');
      //dump($questions);
      if (count($questions[ $type ]) < $v['num']) {
        $this->error('题库中题目数量小于试卷中要求的数量，无法生成数据。' . $qType[ $type ] . count($questions[ $type ]));
      }
    }
    $data = [];
    for ($i = 0; $i < $paperCount; $i++) {
      $paper = [];
      foreach ($qConfig as $type => $v) {
        shuffle($questions[ $type ]);
        $paper = array_merge($paper, array_slice($questions[ $type ], 0, (int)$v['num']));
      }
      $data[] = json_encode($paper);
    }
    $this->result($data, 1);
  }

  /**
   * 查看试卷列表
   */
  public function paperList() {
    $roomId = input('room_id/d', 0, 'abs');
    $room = ($roomId > 0) ? $this->model->find($roomId) : [];
    if (!$room) $this->error('房间不存在');
    //获取题目配置
    $qType = config('question')['type'];
    $qConfig = json_decode($room['q_config'], TRUE);
    $qConfigStr = '';
    foreach ($qConfig as $k => $v) {
      $qConfigStr .= $qType[ $k ] . $v['num'] . '题，每题' . $v['score'] . '分。';
    }
    //获取考卷的信息
    $modelPaper = new Paper();
    $rows = $modelPaper->where('room_id', $roomId)->paginate();

    return view('', [
      'rows'       => $rows,
      'room'       => $room,
      'qConfigStr' => $qConfigStr,
    ]);
  }

  /**
   * @throws \think\db\exception\DataNotFoundException
   * @throws \think\db\exception\ModelNotFoundException
   * @throws \think\exception\DbException
   * 考试开始
   */

  public function examStart() {
    $id = input('id/d', 0, 'abs');
    $row = $id > 0 ? $this->model->find($id) : [];
    if (!$row)
      $this->error('考场不存在');
    if ($row['status'] != 0) {
      $this->error('考试已经开始了，开始时间：' . $row['start_time']);
    }
    //非管理员只能开始自己的班级考试
    if ($this->roleId == 2) {
      $classId = $this->modelClass->getTeacherClassId($this->uid);
      if ($row['class_id'] != $classId)
        $this->error('非管理员只能开始自己的班级考试');
    }
    //查找已经开始的班级
    $startedClass = $this->model->startedClass();
    if ($startedClass) {
      $this->error('目前有考试未结束，请等待，结束时间为' . $startedClass['end_time']);
    }
    //计算开始时间和结束时间
    $now = time();
    $startTime = date('Y-m-d H:i:s', $now);
    $endTime = date('Y-m-d H:i:s', strtotime('+' . $row['exam_duration'] . ' minute', $now));
    $data = ['status'     => 1,
             'start_time' => $startTime,
             'end_time'   => $endTime,
    ];
    $r = $this->model->edit($data, $id);
    if ($r !== FALSE) {
      cmf_log('开始考试', $id, '考场ID' . $id);
//      //记录考试缓存
//      $cacheInfo = [
//        'id'            => $id,
//        'end_time'      => $endTime,
//        'end_time'      => $endTime,
//        'exam_duration' => $row['exam_duration'],
//      ];
//      //考试正在进行中的缓存
//      Cache::set('examInfo', $cacheInfo, new \DateTime($endTime));

      $this->success(lang('success'));
    }
    $this->error(lang('error') . $this->model->getError());
  }

  public function viewPaper() {
    $id = input('id/d', 0, 'abs');
    $paper = $id > 0 ? $this->modelPaper->find($id) : [];
    $qIds = json_decode($paper['questions'],true);
    $answers = json_decode($paper['answers'],true);
    $questions = $this->modelQuestion->getQuestionAnswer($qIds);
    $realname = $this->modelUser->find($paper['uid'])['realname'];
    return view('', [
      'paper'     => $paper,
      'realname'  => $realname,
      'questions' => $questions,
      'answers'   => $answers]);
  }
}
